<?php
/**
 * Created by PhpStorm.
 * User: DD
 * Date: 2016/4/19
 * Time: 0:48
 */

namespace app\admin\services;

use app\common\services\BaseService;
use app\common\services\LoginService;

class AdminService extends BaseService
{
    public function saveRoles($uid, $rids)
    {
        if ($uid) {
            $this->getModelInstance()->where(array('id' => $uid))->setField('role_ids', $rids);
            return true;
        }
        return false;
    }

    public function saveModel($data, $isAdding = null)
    {
        if (!empty($data['id'])) { // for edit
            if (empty($data['password']) || empty(trim($data['password']))) {
                unset($data['password']);
            } else {
                $data['password'] = ccnn_md5($data['password']);
            }
        } else {
            if (empty($data['password']) || empty(trim($data['password']))) {
                $data['password'] = '88888888';
            }
            $data['password'] = ccnn_md5($data['password']);
        }
        return parent::saveModel($data, $isAdding); // TODO: Change the autogenerated stub
    }

    public function pagination($page, $rows, $sort, $order, $filterRules)
    {
        $rt = parent::pagination($page, $rows, $sort, $order, $filterRules); // TODO: Change the autogenerated stub
        $rows = &$rt[1];
        $roleRows = M('role')->getField('id,title', true);
        foreach ($rows as &$row) {
            $role_ids = explode(',', $row['role_ids']);
            $role_names = [];
            foreach ($role_ids as $id) {
                if (!empty($roleRows[$id])) {
                    $role_names[] = $roleRows[$id];
                }
            }
            $row['role_names'] = implode(',', $role_names);
        }
        return $rt;
    }

    public function parseFilterRules($filterRules)
    {
        $rt = parent::parseFilterRules($filterRules); // TODO: Change the autogenerated stub
        if (!empty($rt['role_ids'])) {
            $rt["concat(',',role_ids,',')"] = ['like', '%,' . $rt['role_ids'][1] . ',%'];
            unset($rt['role_ids']);
        }
        $rt['id'] = ['neq', LoginService::getLoginUserId()];
        return $rt;
    }

    public function changePwd($data)
    {
        $old_login_pwd = ccnn_md5($data['old_login_pwd']);
        $login_pwd = ccnn_md5($data['login_pwd']);
        $store_pwd = $this->getModelInstance()->where(['id' => LoginService::getLoginUserId()])->getField('password');
        if ($old_login_pwd != $store_pwd) {
            return [false, '旧密码不正确'];
        }
        $this->getModelInstance()->where(['id' => LoginService::getLoginUserId()])->setField('password', $login_pwd);
        return [true];
    }
}